<template>
  <view>
    <view class="goods-list">
      <view v-for="(goods,i) in goodsList" :key="i" @click="gotoDetail(goods)">
        <my-goods :goods="goods"></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        // 请求参数对象
        queryObj:{
          query:'',
          cid:'',
          pagenum: 1,
          pagesize: 10
        },
        goodsList:[], //商品列表数据
        total:0, //总数量，用来分页
        // 节流阀
        isloading: false
      };
    },
    // 页面加载
    onLoad(options){
      this.queryObj.query = options.query || ''
      this.queryObj.cid = options.cid || ''
      
      this.getGoodsList()
    },
    methods:{
      // 获取商品列表
      async getGoodsList(cb){
        // 打开
        this.isloading = true
        const {data: res} = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
        // 关闭
        this.isloading = false
        // 只要数据请求完毕，按需调用cb回调
        cb && cb()
        if(res.meta.status !== 200) return uni.$showMsg()
        
        // 展开运算符，进行新旧数据拼接
        this.goodsList = [...this.goodsList, ...res.message.goods]
        this.total = res.message.total
      },
      // 跳转到商品详情页面
      gotoDetail(goods){
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + goods.goods_id
        })
      }
    },
    // 上拉触底事件
    onReachBottom() {
      // 判断数据加载完毕
      if(this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg('数据加载完毕！')
      // 判断是否正在加载，防止额外的请求
      if(this.isloading === true) return
      // 页码+1  23条只获取到前22，第3页的1条数据无法获取
      this.queryObj.pagenum++
      this.getGoodsList()
    },
    // 下拉刷新重置
    onPullDownRefresh() {
      // 重置数据
      this.queryObj.pagenum = 1
      this.total = 0
      this.isloading = false
      this.goodsList = []
      // 重新发起请求
      this.getGoodsList(() => uni.stopPullDownRefresh())
    }
  }
</script>

<style lang="scss">

</style>
